﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DnPakExplorer.Controls;

namespace DnPakExplorer.Forms {
	public partial class PanelForm : FormBase {

		private Control mChild;
		private bool mWindowMoving;

		public PanelForm(Control child, string title) {
			InitializeComponent();
			mChild = child;
			child.Visible = true;
			child.Dock = DockStyle.Fill;
			this.Size = new System.Drawing.Size(child.Width+Padding.Horizontal, child.Height+Padding.Vertical);
			this.title.Text = title;
			this.Controls.Add(child);
		}

		protected override void WndProc(ref Message m) {
			switch ((WindowMsg)m.Msg) {
			case WindowMsg.WM_MOVING:
				mWindowMoving = true;
				MyPanel panel = null;
				foreach (Form form in Application.OpenForms) {
					if (form.Visible && form is Equiper) {
						Equiper equiper = (Equiper)form;
						foreach (Control con in form.Controls) {
							if ((panel = con as MyPanel) != null)
								break;
						}
					}
					if (panel != null)
						break;
				}
				if (panel != null) {
					Point pos = panel.PointToClient(Cursor.Position);
					if (panel.TabRectangle.Contains(pos)) {
						this.Opacity = 0.5f;
					} else {
						this.Opacity = 1;
					}
				} else {
					this.Opacity = 1;
				}
				break;
			case WindowMsg.WM_EXITSIZEMOVE:
				this.Opacity = 1;
				if (mWindowMoving) {
					panel = null;
					foreach (Form form in Application.OpenForms) {
						if (form.Visible && form is Equiper) {
							Equiper equiper = (Equiper)form;
							foreach (Control con in form.Controls) {
								if ((panel = con as MyPanel) != null)
									break;
							}
						}
						if (panel != null)
							break;
					}
					if (panel != null) {
						Point pos = panel.PointToClient(Cursor.Position);
						if (panel.TabRectangle.Contains(pos)) {
							int index = panel.PointToTabIndex(pos);
							if (index < 0) {
								index = panel.Controls.Count;
							}

							this.Controls.Remove(mChild);
							panel.AddTab(mChild, title.Text, index);
							panel.SelectedTabIndex = index;
							this.Close();
						}
					} else {

					}

				}
				mWindowMoving = false;
				break;
			case WindowMsg.WM_NCHITTEST:
				mWindowMoving = false;
				break;
			case WindowMsg.WM_WINDOWPOSCHANGING:
				WINDOWPOS param = (WINDOWPOS)Marshal.PtrToStructure(m.LParam, typeof(WINDOWPOS));
				if ((param.flags & Win32.SWP_NOSIZE) != 0 && (param.cx != Width || param.cy!=Height)) {
					mWindowMoving = false;
				}
				break;
			}
			base.WndProc(ref m);
		}
	}
}
